﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WCFMINERP.COM;
using WCFMINERP.Contracts.DataContracts;

namespace WCFMINERP.DownLoad
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            m_SyncContext = SynchronizationContext.Current;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            HelpClass.ShopID = System.Configuration.ConfigurationSettings.AppSettings["shopId"];
            if (config.AppSettings.Settings.AllKeys.Contains("BaseAddress"))
            {
                DataManager.BaseAddress = config.AppSettings.Settings["BaseAddress"].Value;
            }
            txt_File.Text = HelpClass.SaveFilePath;
            txt_adders.Text = DataManager.BaseAddress;
        }

        /// <summary>
        /// 需要下载的文件
        /// </summary>
        List<CusFileInfo> listFile = new List<CusFileInfo>();

        int AlreadyDownloadList = 0;
        /// <summary>
        /// 获取需要下载的文件的线程
        /// </summary>
        Thread getPhoto = null;

        int Time = 10 * 1000; //间隔时间
        int buffersize = 1024;

        int ThreadMaxCount=5; //最大线程数量

        int ThreadCount = 0;  //线程数量
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMain_Load(object sender, EventArgs e)
        {

            lbl_Addres.Text = "";
            lbl_FilePathMess.Text = "";

            getPhoto = new Thread(new ThreadStart(GetDownPhoto));
            getPhoto.Name = "getPhoto";
            getPhoto.Start();
        }

        /// <summary>
        /// 保存地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_adders_Click(object sender, EventArgs e)
        {
            SaveAdders();
        }

        /// <summary>
        /// 保存地址方法
        /// </summary>
        private void SaveAdders()
        {
            if (!string.IsNullOrEmpty(txt_adders.Text) && txt_adders.Text != DataManager.BaseAddress)
            {
                DataManager.BaseAddress = txt_adders.Text;
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings.Remove("BaseAddress");
                config.AppSettings.Settings.Add("BaseAddress", txt_adders.Text);
                config.Save();

                lbl_Addres.Text = "保存成功！";

                //获取要下载的图片
            }
            if (!string.IsNullOrEmpty(txt_adders.Text))
            {
                GetDownPhoto();
            }
        }


        /// <summary>
        /// 获取要下载的图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetDownPhoto()
        {
            if (txt_adders.Text != DataManager.BaseAddress)
            {
                SaveAdders();
            }
            try
            {
                if (listFile.Count == 0)   //没有需要下载的文件
                {
                    listFile = DataManager.Channel.GetFiles(HelpClass.ShopID);
                    if (listFile.Count > 0)
                    {
                        BindMess("检测到"+listFile.Count+"个下载", new CusFileInfo(), false);
                    }
                    AlreadyDownloadList = 0;
                }                
            }
            catch (Exception ex)
            {
                m_SyncContext.Post(delegate
                {
                    lbl_Errer.Text = "发生错误：服务地址不正确"; //ex.Message;
                }, null);
            }   
        }

        SynchronizationContext m_SyncContext = null;

        /// <summary>
        /// 显示信息
        /// </summary>
        private void BindMess(string mess, CusFileInfo model,bool NoError)
        {
            m_SyncContext.Post(delegate
            {
                txt_adders.Enabled = false;
                lbl_Number.Text = AlreadyDownloadList + "/" + listFile.Count;
                lbl_Errer.Text = mess;
               
               float valus=(Convert.ToSingle(AlreadyDownloadList) / listFile.Count) * 100;
                    progressBar1.Value =(valus>100)?100:(int)valus;
                
                if (model != null && model.Photoid > 0)
                {                    
                    if (!NoError)
                    {
                        ListViewItem item = new ListViewItem(new string[] { model.FileName,model.filepath });                                               
                        listView1.Items.Add(item);
                    }
                }
            }, null);  
        }

        /// <summary>
        /// 文件保存地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_saveFiles_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                fbd.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txt_File.Text = fbd.SelectedPath;
                    HelpClass.SaveFilePath = fbd.SelectedPath;

                    lbl_FilePathMess.Text = "保存成功！";
                }
            }
        }

        /// <summary>
        /// 开始下载文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_StartDownload_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(HelpClass.SaveFilePath) || string.IsNullOrEmpty(txt_File.Text))
            {
                MessageBox.Show("设置文件保存路径");
                return;
            }
            Thread t2 = new Thread(new ThreadStart(DownloadStart));
            t2.Name = "DownPhoto";
            t2.IsBackground = true;
            t2.Start();
        }

        /// <summary>
        /// 分配任务
        /// </summary>
        void DownloadStart()
        {            
            while (true)
            {         
                CusFileInfo item = listFile.FirstOrDefault(p => p.NoDownLoad == 0); //0表示没有下载过的，1表示已经下载，2 正在下载，3下载失败
                if (item == null)
                {
                    if (!listFile.Any(p => p.NoDownLoad == 2))
                    {
                        listFile = DataManager.Channel.GetFiles(HelpClass.ShopID);
                        if (listFile.Count > 0)
                        {
                            AlreadyDownloadList = 0;
                            BindMess("检测到"+listFile.Count+"个下载", new CusFileInfo(), false);
                        } 
                    }
                    else
                    {
                        continue;
                    }
                                       
                    if (listFile == null || listFile.Count == 0)
                    {
                        Thread.Sleep(30000);
                        continue;
                    }
                    else
                    {
                        item = listFile.FirstOrDefault(p => p.NoDownLoad == 0); //没有下载过的
                    }
                }
                if (item!=null && item.FileLength > 0)  //文件大小大于0
                {
                    if (ThreadCount < ThreadMaxCount)
                    {
                        Thread t2 = new Thread(new ParameterizedThreadStart(Download));
                        t2.Name = "DownPhoto_" + Guid.NewGuid();
                        t2.IsBackground = true;
                        var task = listFile.FirstOrDefault(p => p.NoDownLoad == 0 && p.Photoid == item.Photoid);
                        if (task != null)
                        {
                            task.NoDownLoad = 2;  //将状态该为正在下载
                        }
                        else
                        {
 
                        }
                        t2.Start(item);

                        ThreadCount++;
                    }
                    
                }
                else
                {
                    //如果有失败的，
                    AlreadyDownloadList++;                   
                    listFile.FirstOrDefault(p => p.NoDownLoad == 0 && p.Photoid == item.Photoid).NoDownLoad = 3;  //将状态该为下载失败 
                    BindMess("下载失败：" + item.FileName, item,false);
                }
            }
        }
        
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="obj"></param>
        void Download(object obj)
        {
            bool b = false;
            CusFileInfo item = obj as CusFileInfo;

            var tmp = item.MapPath.Split('/');
            try
            {               
                long position = 0;
                //string SavelocalFile = HelpClass.SaveFilePath+"\\" + tmp[1];  
                string SavelocalFile = item.filepath.Replace(item.PhotoServerFile, HelpClass.SaveFilePath);  //替换路径
                string localFile=SavelocalFile.Replace(item.FileName, "");
                if (!File.Exists(localFile))
                {
                    Directory.CreateDirectory(localFile);
                }
                using (var fs = new FileStream(SavelocalFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    fs.Position = position;
                    using (var stream = DataManager.Channel.DownloadFileStream(tmp[1], tmp[0], position))
                    {
                       b=CopyStream(stream, fs);
                    }
                }
                if (b)
                {
                    DataManager.Channel.UpdateDownload(HelpClass.ShopID, item.Photoid.ToString(),"1");
                    AlreadyDownloadList++;
                    item.NoDownLoad = 1; //下载成功
                    BindMess("下载成功：" + item.FileName, item, true);
                    ThreadCount--;
                }
            }
            catch (Exception ex)
            {
                m_SyncContext.Post(delegate
                {
                    lbl_Errer.Text = ex.Message;
                }, null);
            }
        }
        
        bool CopyStream(Stream fromstream, Stream tostream)
        {
            bool b = false;
            byte[] buffer = new byte[buffersize];
            int count = 0, offset = 0;
            try
            {
                while ((count = fromstream.Read(buffer, offset, buffersize - offset)) > 0)
                {
                    offset += count;
                    if (offset == buffersize)
                    {
                        tostream.Write(buffer, 0, offset);
                        offset = 0;
                        //SetProgressBar1Value((int)(tostream.Position >> div));
                    }
                }
                if (offset > 0)
                    tostream.Write(buffer, 0, offset);

                b = true;
            }
            catch (Exception ex)
            {
                m_SyncContext.Post(delegate
                {
                    lbl_Errer.Text = ex.Message;
                }, null);
                b = false;
            }
            finally
            {
                   // position = tostream.Position; 
                    fromstream.Dispose();
                    tostream.Dispose();                
            }

            return b;
        }
        
        /// <summary>
        /// 进度
        /// </summary>
        /// <param name="value"></param>
        void SetProgressBar1Value(int value)
        {
            m_SyncContext.Post(delegate
            {
                if (progressBar1.InvokeRequired && progressBar1.IsHandleCreated)
                    progressBar1.BeginInvoke(new Action<int>(SetProgressBar1Value), value);
                else
                    progressBar1.Value = value;
            }, null);
           
        }
    }
}
